package com.it.es.api;

import cn.hutool.json.JSONUtil;
import com.it.es.beans.vo.Account;
import com.it.es.beans.vo.User;
import com.it.es.config.PafcmallElasticsearchConfig;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.Avg;
import org.elasticsearch.search.aggregations.metrics.AvgAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequestMapping("/userApi")
public class UserApi {

    @Autowired
    private RestHighLevelClient client;
    /**
     * 向es中添加数据
     */
    @RequestMapping("/addDate")
    public String addDate() throws IOException {
        // 准备数据
        IndexRequest indexRequest = new IndexRequest("users");//索引名
        // 此处组装对象，可以是别人接口返回的，也可以是前端返回的
        User user = new User();
        user.setUserName("zhangsan");
        user.setAge(18);
        user.setGender("男");
        String jsonString = JSONUtil.parse(user).toString();
        indexRequest.source(jsonString, XContentType.JSON); //要保存的内容

        // 执行操作
        IndexResponse index = client.index(indexRequest, PafcmallElasticsearchConfig.COMMON_OPTIONS);

        // 提取有用的数据相应
        System.out.println(index);


        return "ok";
    }
    /**
     * 检索数据
     */
    @RequestMapping("/searchData")
    public String searchData() throws IOException {
        // 1、创建检索请求
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices("bank");
        // 指定DSL，检索条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchQuery("address","mill"));
        // 聚合数据
        // 1.2）、根据年龄分布聚合
        TermsAggregationBuilder ageAgg = AggregationBuilders.terms("ageAgg").field("age").size(10);
        searchSourceBuilder.aggregation(ageAgg);

        // 1.3）、计算平薪资
        AvgAggregationBuilder balanceAvg = AggregationBuilders.avg("balanceAvg").field("balance");
        searchSourceBuilder.aggregation(balanceAvg);

        System.out.println("检索条件："+searchSourceBuilder.toString());
        searchRequest.source(searchSourceBuilder);

        // 2、执行检索
        SearchResponse searchResponse = client.search(searchRequest, PafcmallElasticsearchConfig.COMMON_OPTIONS);

        // 3、分析结果 searchResponse
        System.out.println(searchResponse.toString());

        //3.1）、获取所有查到的数据
        SearchHits hits = searchResponse.getHits(); // 获取到最外围的 hits
        SearchHit[] searchHits = hits.getHits(); // 内围的 hits 数组
        for (SearchHit hit : searchHits) {
            /**
             * "_index":"bank",
             *        "_type":"account",
             *        "_id":"970",
             *        "_score":5.4032025,
             *        "_source":{
             */
            //            hit.getIndex();hit.getType()''
            String str = hit.getSourceAsString();
            Account account = JSONUtil.parse(str).toBean(Account.class);

            System.out.println(account.toString());

        }
        //3.1）、获取这次检索到的分析数据
        Aggregations aggregations = searchResponse.getAggregations();
        // 可以遍历获取聚合数据
        //        for (Aggregation aggregation : aggregations.asList()) {
        //            System.out.println("当前聚合："+aggregation.getName());
        //            aggregation.getXxx
        //        }
        // 也可使使用下面的方式
        Terms ageAgg1 = aggregations.get("ageAgg");
        for (Terms.Bucket bucket : ageAgg1.getBuckets()) {
            String keyAsString = bucket.getKeyAsString();
            System.out.println("年龄："+keyAsString+" ==> 有 "+bucket.getDocCount()+" 个");
        }

        Avg balanceAvg1 = aggregations.get("balanceAvg");
        System.out.println("平均薪资："+JSONUtil.parse(balanceAvg1).toString());

        return "ok";
    }
}
